

<template>
  <div class="cus-drag-xml" v-if="inited">
<!--    {{state.OPT.widgetConfig}}-->
    <template v-if="state.OPT.widgetConfig && state.OPT.widgetConfig.flat">
<!--      <el-button @click="testLoadTemplate">testLoadTemplate</el-button>-->
      <z-drag-xml :form_slot_content="form_slot_content" :ref="mainRef"

      @editor-leave="onCusDragXmlMouseLeave"
      ></z-drag-xml>
    </template>
    <template v-else>
      不再提供modal模式
    </template>
  </div>

</template>

<script>
import {inject, onMounted, provide, nextTick, toRaw} from 'vue'
import {CustomRenderControlMixin, defineCustomRender} from "@/plugins/form-render/utils/index.js";
import ZDragXml from "@/plugins/z-frame/components/ZDragXml.vue";
import ZEasyModal from "@/plugins/z-frame/components/ZEasyModal.vue";

import {staticTestDrag} from "./static";

export default {
  name: 'CusDragXml',
  components: {ZEasyModal, ZDragXml},
  mixins: [
    CustomRenderControlMixin
  ],
  setup(props, ctx) {
    // console.log('form_slot_content', props.form_slot_content)
    let {part_key} = props.defs
    let JSON5 = ZY.JSON5
    let CusFormExpose = inject('CusFormExpose')
    let form_config = {}
    let drag_xml_uuid = ZY.rid();
    let oldObj = '{}'

    let obj = {}
    let { data, methods, listeners, init, widgetConfig2, buildGetRef, getRef, curFormCon } = defineCustomRender(props, ctx, {
      handleValueInit
    })
    let state = data({
      insVars: []
    })
    init(props)

    let mainRef = buildGetRef('main')

    function handleValueInit(newVal) {
      if (!newVal) {
        newVal = '{}'
      }
      if (newVal) {
        obj = JSON5.parse(newVal)
        // console.log('newVal handleValueInit', obj)
      }
      // console.log('handleValueInit', part_key, obj)
      return newVal
    }

    function onChange() {
      let value = JSON5.stringify(obj)
      // console.log('value', value)
      state.value = value
      methods.onChange(value)
    }

    // let toolApi = useToolApi()


    /**
     * 保存
     * @returns {Promise<void>}
     */
    async function save() {
      let ctx = getRef('main')
      // console.log('call cusDragXml save', ctx)
      if (ctx && ctx.getZProps) {
        obj.props = ctx.getZProps();
        obj.memos = ctx.getMemo();
        obj.oldProps = JSON5.parse(oldObj).props
        onChange()
      }
      return obj
    }

    /**
     * 打开数据展示
     * @returns {Promise<void>}
     */
    async function getZProps() {

      let ctx = getRef('main')
      // console.log('call cusDragXml save', ctx)
      if (ctx && ctx.getZProps) {
        return  ctx.getZProps();
      }
    }

     function getToolState() {

      let ctx = getRef('main')
      if (ctx) {
        return toRaw(ctx.toolState)
      }
    }

    function onClosed(e) {
      curFormCon.callPageEvent('dragxml:closed', {
        save
      }, e)
    }

    function updateFormConfig() {
      let obj = {}
      if (CusFormExpose && CusFormExpose.getPartModel) {
        obj = CusFormExpose.getPartModel()
        let ui = JSON5.parse(obj.ui)
        // console.log('CusFormExpose', ui)
        if (Array.isArray(ui.attrs)) {
          form_config = Object.fromEntries(ui.attrs)
        }
        // console.log(form_config)
      }
    }

    function loadNewObj(_v) {
      oldObj = JSON5.stringify(_v)
      let ctx = getRef('main')
      if (ctx) {
        ctx.importData(_v.memos)
      }
    }

    function loadFromStr(str) {
      let _o = JSON5.parse(str)
      loadNewObj(_o)
    }

    function testLoadTemplate() {
      loadFromStr(staticTestDrag)
    }

    function onCusDragXmlMouseLeave(e) {
      // console.log('onCusDragXmlMouseLeave', e)

      curFormCon.comManager.context.sendEvent('cusdragxml:save', {
        save
      })
    }

    async function onOpened() {
      // console.log('sdsdsds')
      curFormCon.callPageEvent('cusdragxml:opened', {
        save,
        getZProps
      }, {})
      // console.log(obj, ctx)
      state.insVars =  [
      ]
      updateFormConfig()
      loadNewObj(obj);
      let ctx = getRef('main')
      if (ctx) {
        // console.log(ctx.tplManager)
        await ctx.tplManager.loadPlugin(globalThis.importPublicFile('./server1/netZDragCom/index.js'));
        await ZY.sleep(100);
        loadNewObj(obj);
      }
    }

    let curDragXml = {
      getFormConfig() {
        return Object.assign({
          vertical: null,
        }, form_config)
      },
      onZDragxmlReady() {
        // console.log('curDragXml')
        onOpened();
      }
    }

    function setFormConfig(props) {
      let ctx = getRef('main')
      // console.log('setFormConfig', props)
      form_config = props
      nextTick(() => {
        ctx.onSetFormConfig(props)
      })
    }


    document.addEventListener('CusDragXmlUpdate', function () {
      // console.log('sdsdsds')
      let ctx = getRef('main')
      nextTick(() => {
        updateFormConfig()
        setTimeout(() => {
          if (ctx && ctx.onSetFormConfig) {
            ctx.onSetFormConfig()
          }
        }, 300)
      })

    })

    let lifeTimes = {
      onReady() {
        onOpened()
      }
    }

    let ret =  {
      CUS_DRAG_XML: true,
      onChange,
      drag_xml_uuid,
      state,
      mainRef,
      testLoadTemplate,
      lifeTimes,
      loadFromStr,
      onClosed,
      save,
      onCusDragXmlMouseLeave,
      getToolState,
      onOpened,
      // saveData,
      widgetConfig: widgetConfig2,
      methods,
      setFormConfig,
      listeners,
    }

    provide('cusDragXml', curDragXml)

    onMounted(() => {
      let formPage = inject('formPage')
      if (formPage) {
        formPage.registerCom(drag_xml_uuid, ret);
      }
    })



    return ret
  },
}
</script>

